package com.imooc.security.filter;
import com.lambdaworks.crypto.SCryptUtil;
import com.imooc.security.user.User;
import com.imooc.security.user.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName BasicAuthecationFilter
 * @Description TODO 认证
 * @Author wushaopei
 * @Date 2020/10/17 14:20
 * @Version 1.0
 */
@Slf4j
@Component
@Order(2)
@SuppressWarnings("ALL")
public class BasicAuthecationFilter extends OncePerRequestFilter{

    @Autowired
    private UserRepository userRepository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中的认证信息
        String authHeader = request.getHeader("Authorization");
        // 请求进来的时候调用
        // 判断认证信息是否存在，有就进行验证
        if(StringUtils.isNotBlank(authHeader)){
            // 截取认证信息中的basic信息
            String token64 = StringUtils.substringAfter(authHeader,"Basic ");
            String token = new String(Base64Utils.decodeFromString(token64));
            String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(token,":");

            String username = items[0];
            String password = items[1];

            User user = userRepository.findByUsername(username);
//          当前用户不为空与密码正确的情况下，认证通过，并将相关用户数据存入到请求域中
            boolean bo = SCryptUtil.check(password,user.getPassword());
//            if(user != null && StringUtils.equals(password , user.getPassword())){
            if(user != null && bo){
                //认证通过,存放用户信息
                request.getSession().setAttribute("user", user.buildInfo());
                request.getSession().setAttribute("temp","yes");
            }
        }
        try {
            //不管认证是否正确，继续往下走，是否可以访问，交给授权处理
            filterChain.doFilter(request, response);
        }finally {
            // finally 中是响应的时候调用
            HttpSession session = request.getSession();
            if (session.getAttribute("temp")!= null){
                session.invalidate();
            }
        }

    }
}
